let RxJs = require('../../library/reactivex/rx.js');
const storage = require('../../wechat/storage/storage.js');
//队列参数
const list = getApp().list;


//请求队列
const request = (id, options, reactive, requestType) => {
  options.complete = () => {
    list.count--;//进行中的请求数减少
    if (list.wait.length && list.count < 10) {//如果队列中还有请求 并且有空位
      list.count++;//进行中的请求数增加
      let obj = list.wait.splice(0, 1)[0];
      let request;
      if (types.http === requestType) {//出队同时上车
        request = wx.request(obj.options)
      } else if (types.upload === requestType) {
        request = wx.uploadFile(obj.options);
      } else if (types.download === requestType) {
        request = wx.downloadFile(obj.options)
      } else {
        console.error('unkonw request');
      }
      obj.reactive.cancel(() => {
        request.abort();
      });
    }
  };
  if (list.count < 10) {//正在请求的数量少于10 就上车
    list.count++;//进行中的请求数增加
    let request;//上车
    if (types.http === requestType) {
      request = wx.request(options)
    } else if (types.upload === requestType) {
      request = wx.uploadFile(options)
    } else if (types.download === requestType) {
      request = wx.downloadFile(options)
    } else {
      console.error('unkonw request');
    }
    if (request.onProgressUpdate) {
      request.onProgressUpdate((res) => {
        reactive.next(res);
      });
    }
    reactive.cancel(() => {
      request.abort();
    });
  } else {//正在请求的数量大于10
    list.wait.push({ id, options, reactive, requestType });//进队
    reactive.cancel(() => {
      let index = null;
      for (let i of list.wait) {
        if (list.wait[i].id === id) {
          index = i;
          break;
        }
      }
      if (index != null) {
        list.wait.splice(index, 1);
      }
    });
  }
};

const setRequest = (options, requestType) => {
  let id = new Date().getTime() + (list.count + list.wait.length);
  let reactive = RxJs.subject(id);
  options.success = (result) => {
    if (result.statusCode == 200 || result.statusCode == 204) {
      console.log('output from Http 200', result);
      reactive.success(result.data);
    } else if (result.statusCode == 401) {
      // request({
      //   url: config.getUrl(config.api.getSession),//获取Session
      //   headers: {
      //     Authorization: config.words.AUTH + storage.getSync(config.words.AUTH)
      //   },
      //   success: (res) => {
      //     if (result.statusCode == 200) {
      //       storage.set(config.words.SIGN, res.sessionKey);
      //       request(options);
      //     } else {
      //       console.log('output from Http 1err: ', result);
      //       reject(result);
      //     }
      //   },
      //   fail: reject
      // });


    /**
     * @author wqs
     * 
     * @desc 401时清除缓存并重新登陆
     * @desc 优先清除正式缓存
     * 
     * @dataTime 2018年2月7日13:29:52
     */

      storage.removeStorage('devClient');
      storage.removeStorage('client')
        // .then(res=>{
        //   setRequest(options, requestType);
        // })

      console.log('output from Http 401');
      // reactive.success(401);
      
    } else {
      console.log('output from Http 2err: ', result);
      reactive.fail(result);
    }
  };
  options.fail = (err) => {
    if (err.errMsg.indexOf('abort') === -1) {// for now
      reactive.error(err);
    }

    reactive.fail(err);
    console.log('output from Http 3err: ', err);
  };
  request(id, options, reactive, requestType);
  return RxJs.observable(id);
};

const http = (options = {}) => {
  return setRequest(options, types.http);
}

const upload = (options = {}) => {
  return setRequest(options, types.upload);
}

const download = (options = {}) => {
  return setRequest(options, types.download);
}

const types = {
  http: 1,
  upload: 2,
  download: 3
}

const bind = (that) => {
  RxJs = require('../../library/reactivex/rx.js').bind(that);
  return {
    request: http,
  }
}

module.exports = {
  request: http,
  upload,
  download,
  bind
}